<script setup lang="ts">
import { useUserStore } from '@/stores'
import type { FormData } from '@/types'
import service from '@/utils/reuqest'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'

defineComponent({
  name: 'LoginView',
})
const form = ref<FormData>({
  mobile: '13200000000',
  code: '246810',
})
const formRules = ref<FormRules<FormData>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

const formRef = ref<FormInstance>()
console.log(formRef.value)

const router = useRouter()
// const userStore = useUserStore()
const userStore = useUserStore()
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('校验通过')
      const res = await service.post('/v1_0/authorizations', form.value)
      console.log(res)
      // userStore.setToken(res.data.token)
      userStore.setToken(res.data.token)
      router.push('/')
      ElMessage.success('登录成功')
    } else {
      console.log('校验不通过')
    }
  })
}
</script>
<template>
  <div class="container">
    <el-card>
      <img class="logo" src="@/assets/images/logo.png" alt="" />
      <!-- 表单 -->
      <el-form :model="form" :rules="formRules" ref="formRef">
        <el-form-item prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">登 录</el-button>
        </el-form-item>
      </el-form>
      {{ form }}
    </el-card>
  </div>
</template>
<style lang="less" scoped>
.el-form {
  padding: 0 20px;
  .el-button {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 30px;
  }
}
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url('@/assets/images/login.png');

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
  }
}
</style>
